package cn.tnar.parkservice.controller.customer;

import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.model.dto.CloudParkBilling;
import cn.tnar.parkservice.model.dto.CloudParkFeeIndex;
import cn.tnar.parkservice.model.entity.*;
import cn.tnar.parkservice.model.request.MemberGoupReqParam;
import cn.tnar.parkservice.model.response.AccessRuleBaseInfoResponse;
import cn.tnar.parkservice.model.response.CalcBaseInfoResponse;
import cn.tnar.parkservice.model.response.FeesRoleInfoResponse;
import cn.tnar.parkservice.service.*;
import cn.tnar.parkservice.util.DateUtils;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import cn.tnar.pms.kesb.KesbClient;
import cn.tnar.pms.kesb.KesbParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dzx
 * @ClassName:
 * @Description:
 * @date 2019年08月22日 09:43:40
 */
@RestController
@RequestMapping("/service/calcRule")
@Api(tags = "计费规则 - Controller")
@Slf4j
public class CalcFeeRuleController {

    private static final ResultJson RESULT_JSON = new ResultJson();

    @Autowired
    @Qualifier("tParkMemberGroupServiceImpl")
    private ITParkMemberGroupService itParkMemberGroupService;

    @Autowired
    @Qualifier("tParkFeeIndexServiceImpl")
    private ITParkFeeIndexService itParkFeeIndexService;

    @Autowired
    @Qualifier("tParkFeeServiceImpl")
    private ITParkFeeService itParkFeeService;

    @Autowired
    @Qualifier("accessRuleServiceImpl")
    private AccessRuleService accessRuleService;

    @Autowired
    @Qualifier("tCarFeesroleinfoServiceImpl")
    private ITCarFeesroleinfoService itCarFeesroleinfoService;

    @Autowired
    @Qualifier("tParkRegionServiceImpl")
    private ITParkRegionService itParkRegionService;

    @Autowired
    @Qualifier("tParkInfoServiceImpl")
    private ITParkInfoService itParkInfoService;

    @Autowired
    private KesbClient kesbClient;

    @Autowired
    private MqService mqService;

    private final Gson gson = new Gson();

    /*******************************规则配置管理**********************************************/

    /**
     * 根据月卡id查询月卡基本信息，计费索引及计费规则，套餐策略
     *
     * @param json
     * @return ResultJson
     */
    @PostMapping("/baseInfo")
    @ApiOperation("规则配置页面基本展示信息")
    public ResultJson findBaseInfoById(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            Long id = reqParam.getId();
            Map<String, Object> resultMap = new HashMap<String, Object>();
            //根据id查询卡组
            if (id != null) {
                TParkMemberGroup tParkMemberGroup = itParkMemberGroupService.getById(id);
                String parkCode = tParkMemberGroup.getParkCode();
                resultMap.put("parkName", getParkName(parkCode));
                resultMap.put("regionCode", tParkMemberGroup.getRegionCode());
                if (tParkMemberGroup != null) {
                    Long parentId = tParkMemberGroup.getParentId();

                    QueryWrapper<TParkMemberGroup> queryWrapper = new QueryWrapper<TParkMemberGroup>();
                    queryWrapper.eq("id", parentId);
                    TParkMemberGroup parent = null;
                    try {
                        parent = itParkMemberGroupService.getOne(queryWrapper, true);
                    } catch (Exception e) {
                        log.info("子卡的父级节点只能有一个");
                        return getFailResultJson("子卡的父级节点只能有一个");
                    }
                    String parentName = "";
                    if (parent != null) {
                        parentName = parent.getName(); //父节点名称
                    }
                    resultMap.put("parentName", parentName);
                    resultMap.put("name", tParkMemberGroup.getName()); //子卡名称
                    //拿到计费索引的id获取到索引信息 及 计费规则信息
                    Long feeIndexId = tParkMemberGroup.getFeeIndexId();
                    if (feeIndexId != null) {
                        //todo
                        TParkFeeIndex feeIndex = itParkFeeIndexService.getById(feeIndexId);
                        String indexName = "";

                        if (feeIndex != null) {
                            indexName = feeIndex.getName();
                        }
                        final String temp_indexName = indexName;
                        resultMap.put("indexName", indexName);
                        resultMap.put("feeIndex", feeIndex);
                        //获取计费索引区域名称
                        String regionName = "";
                        if (feeIndex != null) {
                            regionName = itParkFeeIndexService.getRegionNameFromSysReg(feeIndex.getRegionCode());
                        }
                        resultMap.put("regionName", regionName);
                        QueryWrapper<TParkFee> feeQueryWrapper = new QueryWrapper<TParkFee>();
                        feeQueryWrapper.eq("index_id", feeIndexId);
                        List<TParkFee> feeList = itParkFeeService.list(feeQueryWrapper);
                        List<CalcBaseInfoResponse> calcs = null;
                        if (feeList != null && feeList.size() > 0) {
                            String regionCodes = tParkMemberGroup.getRegionCode();
                            String regionNames = Arrays.asList(regionCodes.split(",|，"))
                                    .parallelStream()
                                    .filter(StringUtils::isNotBlank)
                                    .map(x -> {
                                        return getRegionName(parkCode, x);
                                    }).collect(Collectors.joining(","));

                            calcs = feeList.parallelStream().filter(x -> x != null)
                                    .map(x -> {
                                        CalcBaseInfoResponse calcBaseInfoResponse = new CalcBaseInfoResponse()
                                                .setId(x.getId())
                                                .setCalcName(temp_indexName)  //暂用计费索引的名称
                                                .setCarType(getCarType(String.valueOf(x.getCartype())))
                                                .setFreeTime(x.getFreetime())
                                                .setLimit(x.getTLimit())
                                                .setRegionCodes(regionCodes)
                                                .setRegionNames(regionNames)
                                                .setWorkType(getWorkType(String.valueOf(x.getWorktype())));
                                        return calcBaseInfoResponse;
                                    }).collect(Collectors.toList());
                        }
                        resultMap.put("calcs", calcs);
                    }
                    //根据套餐策略的id获取套餐策略信息
                    Long feesroleinfoId = tParkMemberGroup.getFeesroleinfoId();
                    FeesRoleInfoResponse feesRoleInfoResponse = null;
                    if (feesroleinfoId != null) {
                        TCarFeesroleinfo tCarFeesroleinfo = itCarFeesroleinfoService.getById(feesroleinfoId);
                        if (tCarFeesroleinfo != null) {
                            feesRoleInfoResponse = new FeesRoleInfoResponse()
                                    .setId(tCarFeesroleinfo.getId())
                                    .setRoleName(tCarFeesroleinfo.getRoleName())
                                    .setAmount(tCarFeesroleinfo.getMonthValue())
                                    .setCardType(getCardType(String.valueOf(tCarFeesroleinfo.getCardType())))
                                    .setCarType(getfeesRoleCarType(String.valueOf(tCarFeesroleinfo.getCarType())))
                                    .setStartTime(tCarFeesroleinfo.getStartTime())
                                    .setEndTime(tCarFeesroleinfo.getEndTime());
                        }
                    }
                    resultMap.put("feesinfo", feesRoleInfoResponse);

                    //根据准入规则的id获取准入规则基本信息
                    Long accessRuleId = tParkMemberGroup.getAccessRuleId();
                    if (accessRuleId != null) {
                        QueryWrapper<AccessRule> accessRuleQueryWrapper = new QueryWrapper<AccessRule>();
                        accessRuleQueryWrapper.eq("access_rule_id", accessRuleId);
                        List<AccessRule> accessRuleList = accessRuleService.list(accessRuleQueryWrapper);
                        //todo 准入规则如何处理返回给前端？
                        AccessRuleBaseInfoResponse accessRuleBaseInfoResponse = null;
                        if (accessRuleList != null && accessRuleList.size() > 0) {
                            //获取一组规则中的第一个规则名称
                            String ruleName = accessRuleList.get(0).getRuleName();
                            String carType = "";
                            String regionCodes = "";
                            String regionNames = "";
                            //拼接车辆类型
//                            carType = accessRuleList.parallelStream()
//                                    .filter(x -> StringUtils.isNotBlank(x.getTemporaryColor()))
//                                    .map(x -> {
//                                        return transTemporaryColor(x.getTemporaryColor());
//                                    }).collect(Collectors.joining(","));
                            carType = transTemporaryColor(accessRuleList.get(0).getTemporaryColor());
                            regionCodes = accessRuleList.parallelStream()
                                    .filter(x -> StringUtils.isNotBlank(x.getRegionCode()))
                                    .map(x -> {
                                        return x.getRegionCode();
                                    }).distinct()
                                    .filter(StringUtils::isNotBlank).collect(Collectors.joining(","));
                            regionNames = accessRuleList.parallelStream()
                                    .filter(x -> StringUtils.isNotBlank(x.getRegionCode()))
                                    .map(x -> {
                                        //Map<String, Object> map = new HashMap<>();
                                        //map.put("regionCode", x.getRegionCode());
                                        //map.put("regionName", getRegionName(parkCode, x.getRegionCode()) );
                                        return getRegionName(parkCode, x.getRegionCode());
                                    }).distinct()
                                    .filter(StringUtils::isNotBlank)
                                    .collect(Collectors.joining(","));
                            accessRuleBaseInfoResponse = new AccessRuleBaseInfoResponse()
                                    .setAccessRuleId(accessRuleId)
                                    .setAccessRuleName(ruleName)
                                    .setCarType(carType)
                                    .setRegionCodes(regionCodes)
                                    .setRegionNames(regionNames);
                        }
                        resultMap.put("accessRule", accessRuleBaseInfoResponse);
                    }
                }
            }
            return getSuccessResultJson(resultMap);
        } catch (
                Exception e) {
            log.error("查询子卡基本信息异常", e);
            return getFailResultJson(false);
        }
    }

    /**
     * 转换套餐策略表的card_type 字段
     *
     * @param cardType
     * @return
     */
    private String getCardType(String cardType) {
        if ("1".equals(cardType)) {
            return "月卡";
        } else if ("2".equals(cardType)) {
            return "季卡";
        } else if ("3".equals(cardType)) {
            return "半年卡";
        } else if ("4".equals(cardType)) {
            return "年卡";
        } else if ("5".equals(cardType)) {
            return "其他卡";
        } else if ("6".equals(cardType)) {
            return "日卡";
        }
        return null;
    }

    /**
     * 转换套餐策略表的car_type字段
     *
     * @param carType
     * @return
     */
    private String getfeesRoleCarType(String carType) {
        //  数据字典：1-小型车，2-中型车，3-大型车，4-电动车，5-摩托车，6-绿牌车',
        if ("1".equals(carType)) {
            return "小型车";
        } else if ("2".equals(carType)) {
            return "中型车";
        } else if ("3".equals(carType)) {
            return "大型车";
        } else if ("4".equals(carType)) {
            return "电动车";
        } else if ("5".equals(carType)) {
            return "摩托车";
        } else if ("6".equals(carType)) {
            return "绿牌车";
        }
        return null;
    }

    /**
     * 转换计费信息表的workType字段
     *
     * @param workType
     * @return
     */
    private String getWorkType(String workType) {
        return "1".equals(workType) ? "工作日" : "非工作日";
    }

    /**
     * 计费规则表的cartype字段转换
     *
     * @param carType
     * @return
     */
//    private String getCarType(String carType) {
//        if ("1".equals(carType)) {
//            return "蓝牌车";
//        } else if ("2".equals(carType)) {
//            return "中型车";
//        } else if ("3".equals(carType)) {
//            return "大型车";
//        } else if ("4".equals(carType)) {
//            return "其他";
//        }
//        return null;
//    }
    private String getCarType(String carType) {
        String carTypeStr = "";
        switch (carType) {
            case "1":
                carTypeStr = "蓝牌车";
                break;
            case "2":
                carTypeStr = "中型车";
                break;
            case "3":
                carTypeStr = "黄牌车";
                break;
            case "4":
                carTypeStr = "电动车";
                break;
            case "6":
                carTypeStr = "绿牌车";
                break;
            case "7":
                carTypeStr = "白牌车";
                break;
            case "8":
                carTypeStr = "黑牌车";
                break;
            default:
                carTypeStr = "";
                break;
        }
        return carTypeStr;
    }


    /**
     * 转换车牌颜色
     *
     * @param temporaryColor
     * @return
     */
    private String transTemporaryColor(String temporaryColor) {
        String[] split = temporaryColor.split(",|，");
        if (split != null && split.length > 0) {
            String collect = Arrays.asList(split).parallelStream()
                    .map(x -> {
                        if ("0".equals(x)) {
                            return "全部";
                        } else if ("1".equals(x)) {
                            return "蓝牌车";
                        } else if ("3".equals(x)) {
                            return "黄牌车";
                        } else if ("6".equals(x)) {
                            return "绿牌车";
                        } else if ("7".equals(x)) {
                            return "白牌车";
                        } else if ("8".equals(x)) {
                            return "黑牌车";
                        } else if ("9".equals(x)) {
                            return "全部不准入";
                        } else {
                            return "";
                        }
                    }).collect(Collectors.joining(","));
            return collect;
        }
        return null;
    }


    /**
     * 获取区域名称
     *
     * @param regionCode
     * @return String
     */
    private String getRegionName(String parkCode, String regionCode) {
        QueryWrapper<TParkRegion> queryWrapper = new QueryWrapper<TParkRegion>();
        queryWrapper.select("name").eq("park_code", parkCode).eq("region_code", regionCode)
                .last("limit 1");
        TParkRegion one = itParkRegionService.getOne(queryWrapper);
        return one != null ? one.getName() : null;
    }


    /**
     * 获取停车场的名称
     *
     * @param parkCode
     * @return
     */
    private String getParkName(String parkCode) {
        QueryWrapper<TParkInfo> queryWrapper = new QueryWrapper<TParkInfo>();
        queryWrapper.select("name")
                .eq("park_code", parkCode)
                .last("limit 1");
        TParkInfo one = itParkInfoService.getOne(queryWrapper);
        return one != null ? one.getName() : null;
    }


    @PostMapping("/calcDetail")
    @ApiOperation("根据计费规则id查询计费规则详情")
    public ResultJson findCalcDetailById(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            Long id = reqParam.getId();
            TParkFee tParkFee = itParkFeeService.getById(id);
            return getSuccessResultJson(tParkFee);
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    @PostMapping("/feesroleInfoDetail")
    @ApiOperation("根据套餐策略id查询套餐策略详情")
    public ResultJson findFeesroleInfoDetailById(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            Long id = reqParam.getId();
            TCarFeesroleinfo tCarFeesroleinfo = itCarFeesroleinfoService.getById(id);
            return getSuccessResultJson(tCarFeesroleinfo);
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    /**
     * 获取停车场下的所有区域
     *
     * @param json
     * @return
     */
    @PostMapping("/getRegions")
    @ApiOperation("获取停车场下的所有区域")
    public ResultJson getRegionsByParkCode(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            String parkCode = reqParam.getParkCode();
            QueryWrapper<TParkRegion> tParkRegionQueryWrapper = new QueryWrapper<TParkRegion>();
            tParkRegionQueryWrapper.eq("park_code", parkCode);
            List<TParkRegion> list = itParkRegionService.list(tParkRegionQueryWrapper);
            List<Map<String, Object>> mapList = null;
            if (list != null && list.size() > 0) {
                mapList = list.parallelStream()
                        .map(x -> {
                            Map<String, Object> map = new HashMap<>();
                            map.put("id", x.getId());
                            map.put("name", x.getName());
                            return map;
                        }).collect(Collectors.toList());
            }
            return getSuccessResultJson(mapList);
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    /**
     * 配置计费规则和计费套餐策略
     *
     * @param json
     * @return ResultJson
     */
    @PostMapping("/configCalcRule")
    @ApiOperation("配置计费规则和计费套餐策略")
    @Transactional
    public ResultJson configCalcRule(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            Long id = reqParam.getId(); //子卡id
            String regionCodes = reqParam.getRegionCodes(); //停车场的区域
            Long feeIndexId = reqParam.getFeeIndexId();  //计费索引id
            Long feesRoleInfoId = reqParam.getFeesRoleInfoId(); //套餐策略id
            String parkCode = reqParam.getParkCode(); //停车场的parkCode
            //判断是否是子卡
            TParkMemberGroup memberGroup = itParkMemberGroupService.getById(id);
            if (memberGroup == null) {
                return getFailResultJson("当前子卡不存在");
            }
            if (new Integer(1).compareTo(memberGroup.getType()) != 0) { //不是子卡
                return getFailResultJson("只有卡证支持计费规则配置");
            }
            //判断是否已经绑定计费索引或者计费规则
//            if (memberGroup.getFeeIndexId() != null || memberGroup.getFeesroleinfoId() != null) {
//                return getFailResultJson("当前卡证已经配置过计费规则，请勿重复配置");
//            }
            if (feeIndexId == null) {
                QueryWrapper<TParkFeeIndex> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("park_code", parkCode).orderByDesc("utime").last("limit 1");
                TParkFeeIndex one = itParkFeeIndexService.getOne(queryWrapper);
                if (one != null) {
                    feeIndexId = one.getId();
                    //查询最新的计费索引是否配置了计费规则
                    QueryWrapper<TParkFee> feeQueryWrapper = new QueryWrapper<>();
                    feeQueryWrapper.eq("index_id", feeIndexId);
                    List<TParkFee> list = itParkFeeService.list(feeQueryWrapper);
                    if (CollectionUtils.isEmpty(list)) {
                        log.error(one.getName() + "计费索引未配置计费规则,请先配置");
                        throw new Exception(one.getName() + "计费索引未配置计费规则,请先配置");
                    }
                }
            }
            Long updateTime = Long.valueOf(DateUtils.getTime());
            TParkMemberGroup tParkMemberGroup = new TParkMemberGroup()
                    .setId(id)
                    .setRegionCode(regionCodes)
                    .setFeeIndexId(feeIndexId)
                    .setFeesroleinfoId(feesRoleInfoId)
                    .setUpdateTime(updateTime);
            boolean b = itParkMemberGroupService.updateById(tParkMemberGroup);
            if (b) {
                //下发卡组
                TParkMemberGroup lowerHairGroup = itParkMemberGroupService.getById(id);
                parkCode = lowerHairGroup.getParkCode();
                String regionCode = lowerHairGroup.getRegionCode();
                if (feesRoleInfoId != null) {
                    TCarFeesroleinfo feesroleinfo = itCarFeesroleinfoService.getById(feesRoleInfoId);
                    if (feesroleinfo != null) {
                        lowerHairGroup.setStartTime(feesroleinfo.getStartTime());
                        lowerHairGroup.setEndTime(feesroleinfo.getEndTime());
                    }
                }
                try {
                    mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.MEMBERGROUP_QUEUENAME_PREFIX + parkCode, gson.toJson(lowerHairGroup));
                } catch (Exception e) {
                    log.error("mq下发卡组失败", e);
                    return getFailResultJson("mq下发卡组失败");
                }
                //下发计费索引
                if (feeIndexId != null) {
                    TParkFeeIndex feeIndex = itParkFeeIndexService.getById(feeIndexId);
                    if (feeIndex != null) {
                        CloudParkFeeIndex cloudParkFeeIndex = genCloudParkFeeIndex(feeIndex, regionCode);

                        //  mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.FEEINDEX_QUEUENAME_PREFIX + parkCode, JSON.toJSONString(cloudParkFeeIndex));
                        QueryWrapper<TParkFee> wrapper = new QueryWrapper<TParkFee>();
                        wrapper.eq("index_id", feeIndexId);
                        //下发计费规则
                        List<TParkFee> list = itParkFeeService.list(wrapper);
                        if (list != null && list.size() > 0) {
                            JSONArray jsonArray = new JSONArray();
                            for (TParkFee tParkFee : list) {
                                CloudParkBilling cloudParkBilling = new CloudParkBilling();
                                cloudParkBilling.setId(tParkFee.getId());
                                cloudParkBilling.setIndex_id(tParkFee.getIndexId());
                                cloudParkBilling.setCartype(tParkFee.getCartype());
                                cloudParkBilling.setFreetime1(tParkFee.getFreetime1());
                                cloudParkBilling.setMonth(tParkFee.getMonth().floatValue());
                                cloudParkBilling.setT_limit(tParkFee.getTLimit().floatValue());
                                cloudParkBilling.setFreetime(tParkFee.getFreetime());
                                cloudParkBilling.setD_type(tParkFee.getDType());
                                cloudParkBilling.setD_preamt(tParkFee.getDPreamt().floatValue());
                                cloudParkBilling.setD_once(tParkFee.getDOnce().floatValue());
                                cloudParkBilling.setD_limit(tParkFee.getDLimit().floatValue());
                                cloudParkBilling.setD_begin(tParkFee.getDBegin().longValue());
                                cloudParkBilling.setD_end(tParkFee.getDEnd());
                                cloudParkBilling.setD_unittime1(tParkFee.getDUnittime1());
                                cloudParkBilling.setD_unittime2(tParkFee.getDUnittime2());
                                cloudParkBilling.setD_unittime3(tParkFee.getDUnittime3());
                                cloudParkBilling.setD_unittime4(tParkFee.getDUnittime4());
                                cloudParkBilling.setD_cycletime1(tParkFee.getDCycletime1());
                                cloudParkBilling.setD_cycletime2(tParkFee.getDCycletime2());
                                cloudParkBilling.setD_cycletime3(tParkFee.getDCycletime3());
                                cloudParkBilling.setD_cycletime4(tParkFee.getDCycletime4());
                                cloudParkBilling.setD_price1(tParkFee.getDPrice1().floatValue());
                                cloudParkBilling.setD_price2(tParkFee.getDPrice2().floatValue());
                                cloudParkBilling.setD_price3(tParkFee.getDPrice3().floatValue());
                                cloudParkBilling.setD_price4(tParkFee.getDPrice4().floatValue());
                                cloudParkBilling.setN_price1(tParkFee.getNPrice1().floatValue());
                                cloudParkBilling.setN_price2(tParkFee.getNPrice2().floatValue());
                                cloudParkBilling.setN_price3(tParkFee.getNPrice3().floatValue());
                                cloudParkBilling.setN_price4(tParkFee.getNPrice4().floatValue());
                                cloudParkBilling.setN_begin(tParkFee.getNBegin());
                                cloudParkBilling.setN_end(tParkFee.getNEnd());
                                cloudParkBilling.setN_limit(tParkFee.getNLimit().floatValue());
                                cloudParkBilling.setN_once(tParkFee.getNOnce().floatValue());
                                cloudParkBilling.setN_preamt(tParkFee.getNPreamt().floatValue());
                                cloudParkBilling.setN_type(tParkFee.getNType());
                                cloudParkBilling.setN_unittime1(tParkFee.getNUnittime1());
                                cloudParkBilling.setN_unittime2(tParkFee.getNUnittime2());
                                cloudParkBilling.setN_unittime3(tParkFee.getNUnittime3());
                                cloudParkBilling.setN_unittime4(tParkFee.getNUnittime4());
                                cloudParkBilling.setN_cycletime1(tParkFee.getNCycletime1());
                                cloudParkBilling.setN_cycletime2(tParkFee.getNCycletime2());
                                cloudParkBilling.setN_cycletime3(tParkFee.getNCycletime3());
                                cloudParkBilling.setN_cycletime4(tParkFee.getNCycletime4());
                                cloudParkBilling.setWorktype(tParkFee.getWorktype());

                                cloudParkBilling.setCount(list.size());
                                cloudParkBilling.setPark_code(parkCode);
                                //cloudParkBilling.setLicensekey("");
                                cloudParkBilling.setUser_type(tParkFee.getUserType());
                                //cloudParkBilling.setCarplatecolor(1);
                                cloudParkBilling.setNewCarType(tParkFee.getCartype());
                                cloudParkBilling.setDelflag(1);

                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("FeeIndex", cloudParkFeeIndex);
                                jsonObject.put("Billing", cloudParkBilling);
                                jsonArray.add(jsonObject);
                                //  mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.TPARKFEE_QUEUENAME_PREFIX + parkCode, jsonArray.toJSONString());
                            }
                            log.info("mq计费下发" + gson.toJson(jsonArray));
                            if (jsonArray != null && jsonArray.size() > 0) {
                                try {
                                    mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.TPARKFEE_QUEUENAME_PREFIX + parkCode, gson.toJson(jsonArray));
                                } catch (Exception e) {
                                    log.error("mq下发计费失败", e);
                                    return getFailResultJson("mq下发计费失败");
                                }
                            }
                        }
                    }
                }
//                //下发套餐策略
//                if (feesRoleInfoId != null) {
//                    TCarFeesroleinfo feesroleinfo = itCarFeesroleinfoService.getById(feesRoleInfoId);
//                    if (feesroleinfo != null) {
//                        mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.FEESROLEINFO_QUEUENAME_PREFIX + parkCode, JSON.toJSONString(feesroleinfo));
//                    }
//                }
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson("卡组配置计费失败");
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson("卡组配置计费失败");
        }
    }

    /**
     * 生成车道计费对应的计费索引实体类
     *
     * @param feeIndex
     * @param regionCodes
     * @return
     */
    private CloudParkFeeIndex genCloudParkFeeIndex(TParkFeeIndex feeIndex, String regionCodes) {
        CloudParkFeeIndex cloudParkFeeIndex = new CloudParkFeeIndex();
        cloudParkFeeIndex.setId(feeIndex.getId());
        cloudParkFeeIndex.setName(feeIndex.getName());
        cloudParkFeeIndex.setAgent_id(String.valueOf(feeIndex.getAgentId()));
        cloudParkFeeIndex.setCashoff(feeIndex.getCashoff());
        cloudParkFeeIndex.setCardoff(feeIndex.getCardoff());
        cloudParkFeeIndex.setMemberoff(feeIndex.getMemberoff());
        cloudParkFeeIndex.setGracetime(feeIndex.getGracetime());
        cloudParkFeeIndex.setUtime(feeIndex.getUtime());
        cloudParkFeeIndex.setUserid(String.valueOf(feeIndex.getUserid()));
        cloudParkFeeIndex.setDelflag(1);//新增
        cloudParkFeeIndex.setCycle(feeIndex.getCycle());
        cloudParkFeeIndex.setRegionCodes(regionCodes);
        return cloudParkFeeIndex;
    }


    @PostMapping("/insertFeeIndex")
    @ApiOperation("新增计费索引")
    @ApiIgnore
    public ResultJson insertFeeIndex(@RequestBody String json) {
        try {
            TParkFeeIndex tParkFeeIndex = JSON.parseObject(json, TParkFeeIndex.class);
            boolean save = itParkFeeIndexService.save(tParkFeeIndex);
            if (save) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }

        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }

    @PostMapping("/updateFeeIndex")
    @ApiOperation("更新计费索引")
    @ApiIgnore
    public ResultJson updateFeeIndex(@RequestBody String json) {
        try {
            TParkFeeIndex tParkFeeIndex = JSON.parseObject(json, TParkFeeIndex.class);
            boolean save = itParkFeeIndexService.updateById(tParkFeeIndex);
            if (save) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }

    @PostMapping("/deleteFeeIndex")
    @ApiOperation("删除计费索引")
    @ApiIgnore
    public ResultJson deleteFeeIndex(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            Long id = reqParam.getId();
            boolean remove = itParkFeeIndexService.removeById(id);
            if (remove) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    @PostMapping("/insertCalcFeeRule")
    @ApiOperation("新增计费规则")
    @ApiIgnore
    public ResultJson insertCalcFeeRule(@RequestBody String json) {
        try {
            TParkFee tParkFee = JSON.parseObject(json, TParkFee.class);
            boolean save = itParkFeeService.save(tParkFee);
            if (save) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }

    @PostMapping("/updateCalcFeeRule")
    @ApiOperation("更新计费规则")
    @ApiIgnore
    public ResultJson updateCalcFeeRule(@RequestBody String json) {
        try {
            TParkFee tParkFee = JSON.parseObject(json, TParkFee.class);
            boolean save = itParkFeeService.updateById(tParkFee);
            if (save) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    @PostMapping("/deleteCalcFeeRule")
    @ApiOperation("删除计费规则")
    @ApiIgnore
    public ResultJson deleteCalcFeeRule(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            Long id = reqParam.getId();
            boolean remove = itParkFeeService.removeById(id);
            if (remove) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    private static final String SERVICE_ID = "85102015";

    /**
     * 接口号：85102015
     * "index_id":"120982",
     * "car_type":"2",
     * "start_time":"20190822093556",
     * "end_time":"20190823093558",
     * "user_type":"0"
     *
     * @param req
     * @return
     */
    @PostMapping("/tryCalc")
    @ApiOperation("试算")
    @ApiIgnore
    public ResultJson tryCalc(@RequestBody KesbParam req) {
        try {
            BigDecimal result = null;
            log.info("试算停车费用:c接口请求参数,param======>" + req);
            Map<String, String> request = kesbClient.request(SERVICE_ID, req);
            log.info("试算停车费用:c接口返回参数,param======>" + request);
            if (request != null && request.size() > 0) {
                result = new BigDecimal(request.get("money"));
            }
            return getSuccessResultJson(result);
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    /**
     * 调用c接口新增计费索引的时候需要传入park code
     *
     * @param json
     * @return
     */
    @PostMapping("/getFeeIndexByParkCode")
    @ApiOperation("/根据停车场查询计费索引")
    public ResultJson getFeeIndexByParkCode(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            String parkCode = reqParam.getParkCode();
            if (StringUtils.isBlank(parkCode)) {
                return getFailResultJson("停车场编号不能为空");
            }
            QueryWrapper<TParkFeeIndex> wrapper = new QueryWrapper<TParkFeeIndex>();
            wrapper.eq("park_code", parkCode).orderByDesc("utime");
            List<TParkFeeIndex> list = itParkFeeIndexService.list(wrapper);
            return getSuccessResultJson(list);
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }

    /**
     * @param json 停车场的custId
     * @return ResultJson
     */
    @PostMapping("/getFeesRoleInfoByCustId")
    @ApiOperation("/根据停车场的custId查询套餐策略")
    public ResultJson getFeesRoleInfoByParkCode(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            String custId = reqParam.getCustId();
            QueryWrapper<TCarFeesroleinfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cust_id", custId).eq("delflag", 1);
            return getSuccessResultJson(itCarFeesroleinfoService.list(queryWrapper));
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    @PostMapping("/insertFeesRoleInfo")
    @ApiOperation("新增套餐策略")
    @ApiIgnore
    public ResultJson insertFeesRoleInfo(@RequestBody String json) {
        try {
            TCarFeesroleinfo tCarFeesroleinfo = JSON.parseObject(json, TCarFeesroleinfo.class);
            boolean save = itCarFeesroleinfoService.save(tCarFeesroleinfo);
            if (save) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }

    @PostMapping("/updateFeesRoleInfo")
    @ApiOperation("更新套餐策略")
    @ApiIgnore
    public ResultJson updateFeesRoleInfo(@RequestBody String json) {
        try {
            TCarFeesroleinfo tCarFeesroleinfo = JSON.parseObject(json, TCarFeesroleinfo.class);
            boolean save = itCarFeesroleinfoService.updateById(tCarFeesroleinfo);
            if (save) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    @PostMapping("/deleteFeesRoleInfo")
    @ApiOperation("删除套餐策略")
    @ApiIgnore
    public ResultJson deleteFeesRoleInfo(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            Long id = reqParam.getId();
            boolean remove = itCarFeesroleinfoService.removeById(id);
            if (remove) {
                return getSuccessResultJson(true);
            } else {
                return getFailResultJson(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    @PostMapping("/getCalcFeeByIndexId")
    @ApiOperation("根据计费索引id查询计费规则信息")
    public ResultJson getCalcFeeByIndexId(@RequestBody String json) {
        try {
            MemberGoupReqParam reqParam = JSON.parseObject(json, MemberGoupReqParam.class);
            QueryWrapper<TParkFee> wrapper = new QueryWrapper<TParkFee>();
            wrapper.eq("index_id", reqParam.getFeeIndexId());
            List<TParkFee> feeList = itParkFeeService.list(wrapper);
            List<CalcBaseInfoResponse> resultList = null;
            if (feeList != null && feeList.size() > 0) {
//                String regionCodes = tParkMemberGroup.getRegionCode();
//                String regionNames = Arrays.asList(regionCodes.split(",|，"))
//                        .parallelStream()
//                        .filter(StringUtils::isNotBlank)
//                        .map(x -> {
//                            return getRegionName(parkCode, x);
//                        }).collect(Collectors.joining(","));
                resultList = feeList.parallelStream().filter(x -> x != null)
                        .map(x -> {
                            CalcBaseInfoResponse calcBaseInfoResponse = new CalcBaseInfoResponse()
                                    .setId(x.getId())
                                    .setCarType(getCarType(String.valueOf(x.getCartype())))
                                    .setFreeTime(x.getFreetime())
                                    .setLimit(x.getTLimit())
                                    .setWorkType(getWorkType(String.valueOf(x.getWorktype())));
                            return calcBaseInfoResponse;
                        }).collect(Collectors.toList());
            }
            return getSuccessResultJson(resultList);
        } catch (Exception e) {
            log.error("error", e);
            return getFailResultJson(false);
        }
    }


    /**
     * 获取失败返回消息体
     *
     * @param data
     * @return
     */
//    private ResultJson getFailResultJson(Object data) {
//        return RESULT_JSON.setCode(ResultCode.FAIL)
//                .setMsg(ResultCode.FAIL_MSG).setData(data);
//    }
    private ResultJson getFailResultJson(Object data) {
        return RESULT_JSON.setCode(ResultCode.FAIL)
                .setMsg(String.valueOf(data)).setData(null);
    }

    /**
     * 获取成功返回消息体
     *
     * @param data
     * @return
     */
    private ResultJson getSuccessResultJson(Object data) {
        return RESULT_JSON.setCode(ResultCode.SUCCESS)
                .setMsg(ResultCode.SUCCESS_MSG).setData(data);
    }


}
